package com.eastfair.venuebooking.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.echo.core.EchoService;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.venuebooking.dto.*;
import com.eastfair.venuebooking.entity.Exhibition;
import com.eastfair.venuebooking.entity.ExhibitionTask;
import com.eastfair.venuebooking.entity.ExhibitionTaskOrg;
import com.eastfair.venuebooking.enumeration.ExhibitionTaskFinishStatusEnum;
import com.eastfair.venuebooking.enums.VenueBookingMoudleEnum;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.ExhibitionSegmentService;
import com.eastfair.venuebooking.service.ExhibitionService;
import com.eastfair.venuebooking.service.ExhibitionTaskOrgService;
import com.eastfair.venuebooking.service.ExhibitionTaskService;
import com.eastfair.venuebooking.vo.ExhibitionTaskVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 任务
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/exhibitionTask")
@Api(value = "ExhibitionTask", tags = "任务")
@PreAuth(replace = "venuebooking:exhibitionTask:")
public class ExhibitionTaskController extends SuperController<ExhibitionTaskService, Long, ExhibitionTask, ExhibitionTaskPageQuery, ExhibitionTaskSaveDTO, ExhibitionTaskUpdateDTO> {

    @Resource
    private EchoService echoService;
    @Resource
    private AttachmentFileFeign attachmentFileFeign;

    @Resource
    private ExhibitionTaskOrgService exhibitionTaskOrgService;

    @Resource
    private ExhibitionService exhibitionService;

    @Resource
    private ExhibitionSegmentService exhibitionSegmentService;

    @Override
    public void handlerResult(IPage<ExhibitionTask> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<ExhibitionTask> exhibitionTaskList = list.stream().map((map) -> {
            ExhibitionTask exhibitionTask = ExhibitionTask.builder().build();
            //TODO 请在这里完成转换
            return exhibitionTask;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(exhibitionTaskList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ExhibitionTaskPageQuery> params) {
        ExhibitionTaskPageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 添加展会任务
     *
     * @param exhibitionSaveDTO 添加展会任务
     * @return
     */
    @ApiOperation(value = "添加展会任务", notes = "添加展会任务")
    @SysLog("添加展会任务")
    @PostMapping("/addExhibitionTask")
    public R addExhibitionTask(@RequestBody @Validated(ExhibitionTaskDTO.Check.class) ExhibitionTaskDTO exhibitionSaveDTO) {
        log.info("addExhibitionTask - 添加展会任务   exhibitionSaveDTO: {}",exhibitionSaveDTO);
        return R.success(baseService.addExhibitionTask(exhibitionSaveDTO));
    }

    /**
     * 修改展会任务
     *
     * @param exhibitionUpdateDTO 修改展会任务
     * @return
     */
    @ApiOperation(value = "修改展会任务", notes = "修改展会任务")
    @SysLog("修改展会任务")
    @PostMapping("/updateExhibitionTask")
    public R updateExhibitionTask(@RequestBody @Validated(ExhibitionTaskDTO.Check.class) ExhibitionTaskDTO exhibitionUpdateDTO) {
        log.info("updateExhibitionTask -  修改展会任务  exhibitionUpdateDTO: {}",exhibitionUpdateDTO);
        return R.success(baseService.updateExhibitionTask(exhibitionUpdateDTO));
    }

    @ApiOperation(value = "展会任务列表", notes = "展会任务列表")
    @PostMapping("/queryExhibitionTaskList")
    public R<IPage<ExhibitionTaskVO>> queryExhibitionTaskList(@RequestBody @Validated(ExhibitionTaskQuery.Check.class)PageParams<ExhibitionTaskQuery> params) {
        log.info("queryExhibitionTaskList - 展会任务列表   params: {}",params);
        return R.success(baseService.queryExhibitionTaskList(params));
    }

    /**
     * 删除任务
     *
     * @param taskId 删除任务
     * @return
     */
    @ApiOperation(value = "删除任务", notes = "删除任务")
    @SysLog("删除展会任务")
    @GetMapping("/removeExhibitionTask")
    public R removeExhibitionTask(@RequestParam("taskId") @Validated @NotNull(message = "任务ID必填") Long taskId) {
        log.info("removeExhibitionTask - 删除任务   taskId: {}",taskId);
        ExhibitionTask exhibitionTask = baseService.getById(taskId);
        ExhibitionTask task = new ExhibitionTask();
        task.setId(taskId);
        task.setIsDeleted(BusinessConstant.YES);
        task.setIsEnabled(BusinessConstant.NO);
        // 删除关联关系
        UpdateWrapper<ExhibitionTaskOrg> uw = new UpdateWrapper<>();
        uw.lambda().eq(ExhibitionTaskOrg::getTaskId,taskId).set(ExhibitionTaskOrg::getIsDeleted,BusinessConstant.YES).set(ExhibitionTaskOrg::getIsEnabled,BusinessConstant.NO);
        exhibitionTaskOrgService.update(uw);
        boolean b = baseService.updateById(task);
        // 修改原绑定环节id的是否可删除状态
        exhibitionSegmentService.updateDeleteAble(exhibitionTask);
        return R.success(b);
    }

    /**
     * 修改任务完成状态
     *
     * @param taskId 任务id
     * @return
     */
    @ApiOperation(value = "修改任务完成状态", notes = "修改任务完成状态")
    @SysLog("修改展会任务完成状态")
    @GetMapping("/updateFinishStatus")
    public R updateFinishStatus(@RequestParam("taskId") @Validated @NotNull(message = "任务ID必填") Long taskId,@RequestParam("finishStatus") @Validated @NotNull(message = "任务完成状态必填") ExhibitionTaskFinishStatusEnum finishStatus) {
        log.info("taskId: {} 修改任务完成状态为: {}",taskId,finishStatus);
        ExhibitionTask task = new ExhibitionTask();
        task.setId(taskId);
        task.setFinishStatus(finishStatus);
        return R.success(baseService.updateById(task));
    }

    /**
     * 添加任务附件
     *
     * @param attachmentFileDTO 添加任务附件
     * @return
     */
    @ApiOperation(value = "添加任务附件", notes = "添加任务附件")
    @SysLog("添加展会任务附件")
    @PostMapping("/saveAttachmentFile")
    public R saveAttachmentFile(@RequestBody AttachmentFileDTO attachmentFileDTO) {
        log.info("saveAttachmentFile - 添加任务附件   attachmentFileDTO: {}",attachmentFileDTO);
        attachmentFileDTO.setBusinessType(VenueBookingMoudleEnum.EXHIBITION_TASK.getCode());
        return attachmentFileFeign.addAttachmentFile(Collections.singletonList(attachmentFileDTO));
    }

    /**
     * 删除任务附件
     *
     * @param id 附件id
     * @return
     */
    @ApiOperation(value = "删除任务附件", notes = "删除任务附件")
    @SysLog("删除展会任务附件")
    @GetMapping("/deleteAttachmentFile")
    public R deleteAttachmentFile(@RequestParam("id") @Validated @NotNull(message = "附件ID必填") Long id) {
        log.info("deleteAttachmentFile - 删除任务附件   id: {}",id);
        return attachmentFileFeign.detele(id);
    }

    /**
     * 导出任务书
     * @param response
     */
    @GetMapping("/exportTask")
    public void exportTask(@RequestParam("exhibitionId") @Validated @NotNull(message = "展会ID不能为空")Long exhibitionId,
                           @RequestParam("exportType") @Validated @NotNull(message = "请选择导出类型")Integer exportType, HttpServletResponse response) {
        log.info("exportTask - 导出任务书   exhibitionId: {},exportType: {}",exhibitionId,exportType);

        try {
            // 查询对应展会
            Exhibition exhibition = exhibitionService.getById(exhibitionId);
            if (Objects.nonNull(exhibition)) {

                switch (exportType) {
                    case 1:
                        // 通过展会环节导出
                        baseService.exportBySegment(response, exhibition);
                        break;
                    case 2:
                        // 通过服务部门导出
                        baseService.exportByOrg(response, exhibition);
                        break;
                    case 3:
                        // 通过场地导出
                        baseService.exportBySpace(response, exhibition);
                        break;
                    default:
                        break;
                }
            } else {
                throw BizException.wrap(VenueBookingExceptionCode.EX_NOT_FIND_EXHIBITION);
            }

        } catch (Exception e) {
            log.error(VenueBookingExceptionCode.EXPORT_ERROR.getMsg(),e);
            throw BizException.wrap(VenueBookingExceptionCode.EXPORT_ERROR);
        }

    }

}
